package com.test;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import com.entity.User;
import com.factory.HibernateSessionFactory;

public class Demo1 {
	
	@Test
	public void test1() throws Exception{
		Session s = null;
		Transaction tx = null;
		try {
		//读取并解析配置信息
		/*
		 * 方式：
		 * 1.Configuration conf = new Configuration().configure();
		 * 	读取在src目录下的默认配置文件：hibernate.cfg.xml
		 * 2.Configuration conf = new Configuration().configure(String fileName);
		 * 	读取fileName路径下的配置文件
		 * 3.Configuration conf = new Configuration();//读取src的配置文件hibernate.properties配置文件。
		 * 	 conf.addClass(Class clazz);//将实体类加载
		 *	 配置文件格式：
		 *	hibernate.dialect=org.hibernate.dialect.MySQLDialect
		 *	hibernate.connection.url=jdbc\:mysql\://localhost\:3306/hib_db
		 *	hibernate.connection.username=root
		 *	hibernate.connection.password=root
		 *	hibernate.connection.driver_class=com.mysql.jdbc.Driver
		 *
		 */
		Configuration conf = new Configuration();
		conf.addClass(User.class);
		//读取并映射信息
		SessionFactory sf = conf.buildSessionFactory();
		//打开Session
		s = sf.openSession();
		//开始一个事务
		tx = s.beginTransaction();
		//数据库操作：插入一条记录
		s.save(new User("lisi", 12, "zhongguoxian",new Date()));
		//提交事务
		tx.commit();
		} catch(Exception e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			if(s != null) s.close();
		}
		
	}
	
	@Test
	public void test2() {
		Configuration conf = new Configuration().configure();
		SessionFactory sf = conf.buildSessionFactory();
		Session s = sf.openSession();
		Transaction tx = s.beginTransaction();
		
		User user = (User) s.get(User.class, 1);
		
//		user.setAge(100);
//		s.update(user);
		s.delete(user);
		
		tx.commit();
	}
	
	@Test
	public void test3() {
		Session s = HibernateSessionFactory.getSession();
		Query query = s.createQuery("from User");
		List<User> listUser = query.list();
		for (User user : listUser) {
			System.out.println(user.getAddress() + user.getUname());
		}
		HibernateSessionFactory.closeSession();
	}
}
